<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class LinkToVendor extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	public function index($vendorid)
	{
		$data['vendorid'] = $vendorid;
		$this->load->view('v_linktovendor', $data);
	}
	
	public function link($vendorid)
	{
		$this->load->model('m_linktovendor');
		$data['vendorid'] = $vendorid;
		
		$recordset = $this->m_linktovendor->get_user_id($this->session->userdata('useremail'));
		$results = $recordset->result();
		$userid = $results[0]->userId;

		$accountNumber = $this->input->post('accountNumber', TRUE);
		$billingZip = $this->input->post('billingZip', TRUE);
		$last4ssn = $this->input->post('last4ssn', TRUE);
		
		$url = "http://localhost/cecs492/prototype/vendorservice/vendorAPI/linkToVendor";
		

		$postdata = http_build_query(
			array(
				'userid' => $accountNumber,
				'billingZip' => $billingZip,
				'last4ssn' => $last4ssn,
				'vendorname' => 'Verizon'
			)
		);
		
		$json = NULL;

		if(function_exists("curl_init"))
		{
			$curl_handle = curl_init();
			curl_setopt ($curl_handle, CURLOPT_POST, TRUE);
			curl_setopt ($curl_handle, CURLOPT_POSTFIELDS, $postdata);
			curl_setopt ($curl_handle, CURLOPT_URL, $url);
			curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
			curl_setopt ($curl_handle, CURLOPT_CONNECTTIMEOUT, TRUE);
			$json = curl_exec($curl_handle);
			curl_close($curl_handle);
		}
		else
		{
			$opts = array('http' =>
				array(
					'method'  => 'POST',
					'header'  => 'Content-type: application/x-www-form-urlencoded',
					'content' => $postdata
				)
			);
			
			$context  = stream_context_create($opts);

			$json = file_get_contents($url, false, $context);
		}

		$vendorObject = json_decode($json);

		if(isset($vendorObject->code) && $vendorObject->code == 0)
		{
		
			$this->m_linktovendor->link($vendorid, $userid, $accountNumber);
					
			$this->load->view('v_vendors');
		}
		else
		{
			$this->load->view('v_linktovendor', $data);
		}
	}
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */